package com.atguigu.service;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserService
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-03
 * @Description:
 *
 * UserDetailsService:在进行自定义登录页面的时候，必须要实现这个接口
 */
@Component
public class UserService implements UserDetailsService {

    static Map<String,com.atguigu.pojo.User> map =  new HashMap();

    static {
        com.atguigu.pojo.User user1 =   new com.atguigu.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("$2a$10$DU8AieP2oCXEik461Gqnd.gq37EXNhOXTBCtbCZwR5jTCfNw3VsQK");
        user1.setTelephone("111");

        com.atguigu.pojo.User user2 =   new com.atguigu.pojo.User();
        user2.setUsername("zhangsan");
        user2.setPassword("$2a$10$oilam.6igGMoCQQkxW4S5O44huXbxvSBd69.aug55xWKgplSPVSiW");
        user2.setTelephone("222");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }


    /**
     *
     * @param username 表示用户登录的名字
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名，进入到数据库进行查询
        com.atguigu.pojo.User userInfo = map.get(username);
        // 判断当前用户是否有值
        if (userInfo == null){
            // 说明数据库里面没有这个数据
            return null;
        }
        // 说明用户已经注册，并在数据库里面有当前用户
//        String password = "{noop}" +  userInfo.getPassword();
        String password =   userInfo.getPassword();
        List<SimpleGrantedAuthority> lists = new ArrayList<>();
//        lists.add(new SimpleGrantedAuthority("ROLE_abc"));
        lists.add(new SimpleGrantedAuthority("add"));
        lists.add(new SimpleGrantedAuthority("delete"));
        lists.add(new SimpleGrantedAuthority("ROLE_ADMIN"));


        return new User(username,password,lists);
    }
}